<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-27 14:19
 * Modified Time: 2019-06-27 14:19
 * Version: 2.0
 */

namespace App\Modules\Order\Repositories;


use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Models\Appointment;
use App\Modules\Member\Repositoryies\MemberRepository;
use App\Modules\Order\Criterias\AppointmentCriteria;
use App\Modules\Order\Validators\AppointmentValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class AppointmentRepository extends BaseRepository
{
	public function model()
	{
		return Appointment::class;
	}

	public function validator()
	{
		return AppointmentValidator::class;
	}

	/**
	 * 获取预约某天或者某时间段的预约
	 * @param $requestData
	 * @return mixed
	 */
	public function getAppointmentList($storeId,$barberId,$date=null,$startDay=null,$endDay=null)
	{
		return $this->getByCriteria(new AppointmentCriteria($storeId,$barberId,$date,$startDay,$endDay));
	}


	/**
	 * 订单预约个数
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function getAppointmentCount($storeId, $userId = 0)
	{
		$where = empty($userId) ? [
			'store_id' => $storeId,
			'status'   => 0
		] : [
			'barber_id' => $userId,
			'store_id'  => $storeId,
			'status'    => 0
		];
		return $this->model->where($where)->whereDate('created_at', date("Y-m-d"))->count();
	}


	/**
	 * 计算当天预约的个数
	 * @param $storeId
	 * @param array $dateList
	 * @return mixed
	 */
	public function orderCountsByDate($storeId,$dateList=[]){
		$model =  $this->model->where([
			'store_id' => $storeId,
			'status'=> ['in'=>[0,1]]
		]);
	    $model = empty($dateList) ? $model->whereDate('created_at', date("Y-m-d")) : $model->whereDate('created_at','>=',$dateList['end_date'])->whereDate('created_at','<=',$dateList['start_date']);
		return    $model->count();
	}








	/**
	 * 预约是否已经存在
	 */
	public function isExitedByAppointmentInfo($storeId, $barberId, $appointmentTime)
	{
		$info = $this->model->where(['store_id' => $storeId, 'barber_id' => $barberId, 'appointment_time' => (strtotime($appointmentTime)+1)])->whereIn('status',[config('constant.orderAppointmentStatus.create'),config('constant.orderAppointmentStatus.receive')])->first();
		if (!empty($info)) {
			throw  new AllValidatorException(['msg' => '预约时间冲突，请重新预约']);
		};
		return $info;
	}

	/**
	 * 新增预约订单
	 * @param $storeId
	 * @param $barberId
	 * @param $appointmentTime
	 * @param $mobile
	 * @param null $serviceId
	 * @param null $serviceName
	 * @param null $servicePrice
	 * @param null $payment
	 * @param int $source
	 * @param null $nickname
	 * @param null $memberId
	 * @param null $memberCard
	 * @param int $status
	 * @return mixed
	 */
	public function addAppointmentOrder($storeId, $barberId, $appointmentTime, $mobile, $serviceId = null, $serviceName = null, $servicePrice = null, $payment = null, $source = 1, $nickname = null, $memberId = null,$remark=null, $memberCard = null, $status = 0)
	{
		$params = [
			'store_id'         => $storeId,
			'barber_id'        => $barberId,
			'service_id'       => $serviceId,
			'service_name'     => $serviceName,
			'member_id'        => $memberId,
			'member_card'      => $memberCard,
			'source'           => $source,
			'price'            => $servicePrice,
			'payment'          => $payment,
			'appointment_time' => strtotime($appointmentTime)+1,
			'mobile'           => $mobile,
			'nick'             => $nickname,
			'expire'           => (time() + config('constant.orderCancelTimeMin')*60),
			'status'           => $status,
			'remark'           => $remark
		];
		return $this->create($params);
	}

	/**
	 * 预约订单是否存在
	 * @param $id
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function isExisted($id)
	{
		$appointmentInfo = $this->find($id);
		if (empty($appointmentInfo)) {
			throw  new NotFoundException(['msg' => '预约信息不存在，请再次确认！']);
		}
		return $appointmentInfo;
	}


	/**
	 * 预约修改状态 取消预约处理
	 * @param $appointmentId
	 * @param $status
	 * @param $cancelType
	 * @param $remark
	 * @return mixed
	 */
	public function updateAppointmentCancel($appointmentId, $status, $cancelType, $remark)
	{
		$params = [
			'status'      => $status,
			'cancel_type' => $cancelType,
			'remark'      => isset($remark) ? $remark : ''
		];
		return $this->model->where(['id'=>$appointmentId])->update($params);
	}


	/**
	 * 订单是否被确认
	 * @param $appointmentId
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function isConfirmed($appointmentId)
	{
		$res = $this->isExisted($appointmentId);
		if($res->status == 1){
			throw  new NotFoundException(['msg' => '该预约订单已经确认过,且开单。请勿重复操作！']);
		}
		return $res;
	}

	/**
	 * 预约完成
	 * @param $appointment_id
	 * @return mixed
	 * @throws NotFoundException
	 */
	public function complete($appointment_id)
    {
	    $res = $this->isConfirmed($appointment_id);
        $res->status = 1;
        $res->save();
        return true;
    }
}